import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;



/*
 * QueryResult is a class designed to accumulate tiles with the same documentID:paragraphID pair 
 * and then process them into the proper display text.  The ranking is determined by number of tiles in the result, 
 * but order of displayed results is processed by a different class, presumably by ranking.  
 * 
 * Ranking right now is set to # of tiles (matches) to the query.  
 */
public class QueryResult {
	ArrayList<WordTile> tiles;
	File collection;
	String query;
	public QueryResult(File collection){
		this.tiles = new ArrayList<WordTile>();
		this.collection = collection;
		query = null;
	}
	
	
	public void addtile(WordTile tile){
		tiles.add(tile);
		query = QueryDB.queryAND(query,  tile.getWord());  //add this word to the query.  
	}
	
	public int getWeight(){
		return tiles.size();
	}
	
	public int compareTo(QueryResult other){
		return this.getWeight() - other.getWeight();
	}
	
	//ASSUMES that all tiles added are in the same paragraph
	public String getText(){
		if(tiles.size() == 0)
			return "No Results Found";

		
		StringBuffer resultText = new StringBuffer();
		
		WordTile tile = tiles.get(0);
		resultText.append("Document ").append(tile.getdocId());
		resultText.append("  Paragraph ").append(tile.getparaId());
		resultText.append("  Relevance ").append(getWeight()).append("\n");
		
		resultText.append(getParagraph(tile));
		
		return resultText.toString();
	}


	/*
	 * This function randomly accesses the file designated by the collection variable to retrieve the paragraph indicated by the tile. 
	 */
	private String getParagraph(WordTile tile) {

		String text = null;
		try{
			RandomAccessFile br = new RandomAccessFile(collection,"r"); 
			br.seek(tile.getparaLoc());
			text = br.readLine();  // ASSUMPTION: Paragraphs are on single lines.
			br.close();
		}
		catch(Exception e){
			return "Unable To Access Collection: "+collection+"\n";
		}
		return wrapText(text, 80);
	}


	public static String wrapText(String text, int lineLength) {
		
		if(lineLength < 1) return text;
		if(text.length() < lineLength) return text;
		
		StringBuffer newText = new StringBuffer();
		
		
		int start = 0;
		int end;
		int totlength = text.length();
		int charsleft = totlength - start;
		while(charsleft > 0){
			if(charsleft > lineLength){
				end = start + lineLength;
				while(text.charAt(end-1) != ' ')
					end--;
			} else 
				end = totlength;
			newText.append(text.subSequence(start,  end)).append("\n");
			start = end;
			charsleft = totlength - start;
		}
		
		return newText.toString();
	}


	//queries are assembled through QueryDB and are therefore in canonical form.  
	public boolean matchesQuery(String query) {
		return this.query.compareTo(query) == 0;
	}
}
